package org.jsrml.sv.mob.controller.index;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jsrml.common.util.JSONResultDTO;
import org.jsrml.core.base.dto.LoginDomanDTO;
import org.jsrml.core.base.entity.Resource;
import org.jsrml.core.base.entity.Role;
import org.jsrml.core.base.qo.ResourceQO;
import org.jsrml.core.base.qo.RoleQO;
import org.jsrml.core.base.service.ResourceService;
import org.jsrml.core.base.service.RoleService;
import org.jsrml.core.purchaser.entity.Worker;
import org.jsrml.core.purchaser.qo.WorkerQO;
import org.jsrml.core.purchaser.service.WorkerService;
import org.jsrml.sv.mob.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/main")
public class mainController extends BaseController {

	@Autowired
	private ResourceService resourceService;
	
	@Autowired
	private WorkerService workerService;
	
	@Autowired
	private RoleService roleService;

	@RequestMapping(value = "/menu", method = RequestMethod.POST)
	@ResponseBody
	public JSONResultDTO menuInRole() {
		try {
			Subject subject = SecurityUtils.getSubject();
			LoginDomanDTO dto = new LoginDomanDTO();
			if (subject.isAuthenticated()) {
				try {
					BeanUtils.copyProperties(dto, subject.getPrincipal());
				} catch (IllegalAccessException e) {
				} catch (InvocationTargetException e) {
				}
			}

			List<String> roleIds = new ArrayList<String>();
			ResourceQO resourceQO = null;
			List<Resource> list = null;

			switch (dto.getAccountOwner()) {
			case "worker":
				WorkerQO qo = new WorkerQO();
				qo.setId(dto.getId());
				qo.setFetchRoles(true);
				Worker worker = workerService.queryUnique(qo);
				for (Role role : worker.getRoles()) {
					roleIds.add(role.getId());
				}

				if (roleIds.isEmpty())
					break;

				RoleQO roleQO = new RoleQO();
				roleQO.setFetchResources(true);
				roleQO.setIds(new ArrayList<String>(roleIds));
				List<Role> roles = roleService.queryList(roleQO);
				list = new ArrayList<Resource>();
				for (Role r : roles) {
					list.addAll(r.getResources());
				}
				break;
			case "vendor":
				resourceQO = new ResourceQO();
				resourceQO.setSystem("system2");
				list = resourceService.queryList(resourceQO);
				break;
			case "admin":
				resourceQO = new ResourceQO();
				resourceQO.setSystem("system1");
				list = resourceService.queryList(resourceQO);
				break;
			default:
				break;
			}
			return createSuccessResult(list);

		} catch (Exception e) {
			return createFailResult("-1", e.getMessage(), null);
		}
	}

}
